﻿using CallNumberSystem;

using GeuERP.Common;

using NxStoreManage;

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LengthAiCalculate
{
    public partial class ManufactureFrm : BaseForm
    {
        private bool Start = false;

        private SumResult sumResult;

        private EditManufacture editManufacture;

        private static Dictionary<string, (string userName, string phoneNum)> NoteUser = new Dictionary<string, (string userName, string phoneNum)>();

        private int NoteNum = 1;

        public static string isSave = "(1)";

        public ManufactureFrm()
        {
            InitializeComponent();
            addCutGroup = new AddCutGroup();
            addCutGroup.SuccessAction += Reload;
            editManufacture = new EditManufacture();
            editManufacture.DelSuccess = Reload;
            SetShowFormDefault(addCutGroup);
            SetShowFormDefault(editManufacture);
            SetDataGridDefault(dataGridView1, rowHeadersVisible: false, autoGenerateColumns: false);
            SetDataGridDefault(dataGridView2, rowHeadersVisible: false, autoGenerateColumns: false, autoSizeColumnsMode: DataGridViewAutoSizeColumnsMode.Fill);
            SetDataGridDefault(dataGridView3, rowHeadersVisible: false, autoGenerateColumns: false, enableSort: false);
            timer2.Interval = 1000;
            timer2.Enabled = true;
        }

        private void BindComb1()
        {
            BindComboBox(comboBox1, $@"SELECT DISTINCT p.lineCode,p.lineName FROM [PM.Ai] a INNER JOIN [PM.PlanMain] p ON a.planID = p.planID WHERE a.isSave IN {isSave} AND a.isEnd = 0 AND  p.lineCode=1");
        }

        private void ManufactureFrm_Load(object sender, EventArgs e)
        {
            toolStripStatusLabel5.Text = "  软件版本:" + SysInit.GetVersion();
            nxsqlHelper.ExcuteSql($@"UPDATE [PM.Ai]
            SET isEnd = 1,
                isSave = 1
            WHERE planName IN
                  (
                      SELECT KZH
                      FROM {SysInit.GetSBServer()}SB_StoreOut
                      WHERE T = 1
                  )
                  AND isEnd = 0;
            UPDATE [PM.PlanMain]
            SET [state] = 2
            WHERE planName IN
                  (
                      SELECT KZH
                      FROM {SysInit.GetSBServer()}SB_StoreOut
                      WHERE T = 1
                  )
                  AND [state] <> 2;");

            BindComb1();
            if (SysInit.SocketServer == null || !SysInit.SocketServer.SocketIsOK)
            {
                SysInit.SocketServer = new SocketServerHelper(IPAddress.Any, SysInit.SocketPort, (str) =>
               {
                   Invoke(new Action(() =>
                   {
                       if (Start)
                       {
                           double.TryParse(str, out var lg);

                           //double.TryParse(textBox5.Text, out var p);
                           //lg = lg * (100 - p) / 100;
                           //var s = (int)(lg / 0.5);
                           //var jg = s * 5 / 10.0;
                           //textBox2.Text = jg.ToString("0.0");
                           textBox2.Text = lg.ToString();
                           OP();
                       }
                   }));
               }, null, WatchClientConnection: (clientId) =>
               {
                   Invoke(new Action(() =>
                   {
                       toolStripStatusLabel3.Text = "测长仪:" + clientId + "已连接";
                       toolStripStatusLabel3.ForeColor = Color.White;
                       toolStripStatusLabel3.BackColor = Color.Green;
                   }));
               }, WatchClientClose: (clientId) =>
               {
                   Invoke(new Action(() =>
                   {
                       toolStripStatusLabel3.Text = "测长仪:" + clientId + "已断开连接";
                       toolStripStatusLabel3.ForeColor = Color.Red;
                       toolStripStatusLabel3.BackColor = Color.White;
                   }));
               });
            }
            Task.Run(() =>
            {
                DataTable dt = nxsqlHelper.GetDataTableFromSql("SELECT pu.userCode,pu.phoneNum,u.userName FROM [PM.AddPlanMsgUser] pu LEFT JOIN Nx_User u ON u.userCode = pu.userCode ");
                foreach (DataRow item in dt.Rows)
                {
                    if (!NoteUser.ContainsKey(item["userCode"].ToString().Trim()))
                    {
                        NoteUser.Add(item["userCode"].ToString().Trim(), (userName: item["userName"].ToString().Trim(), phoneNum: item["phoneNum"].ToString().Trim()));
                    }
                }
            });
            NoteAddPlan();
            if (DateTime.Now.Hour >= 20 && DateTime.Now.Hour <= 23)
            {
                dateTimePicker1.Value = DateTime.Now.AddDays(1);
            }
            else
            {
                dateTimePicker1.Value = DateTime.Now;
            }
            GetStoreRealMainID(hotStoreRealMainIDNum);
        }

        private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindComboBox(comboBox2, $"SELECT [mID],planSize + '(' + planSteel + ')' + '(' + [planName] + ')' planstring FROM [PM.Ai] WHERE isSave IN {isSave} AND isEnd=0 AND lineName='{comboBox1.Text}' ORDER BY orderBy DESC");
        }

        private void ComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Reload();
        }

        public void RefreshData(bool isRightBtn)
        {
            BindComboBox(comboBox1, $@"SELECT DISTINCT p.lineCode,p.lineName FROM [PM.Ai] a INNER JOIN [PM.PlanMain] p ON a.planID = p.planID WHERE a.isSave = 1 AND a.isEnd = 0");
            Reload();
        }

        private int dg1SelectIndex = 0;

        /// <summary>
        /// 获取历史炉号单数量
        /// </summary>
        private int hotStoreRealMainIDNum = 6;

        private void Reload(bool isRightBtn = false)
        {
            string numWhere = "";
            if (checkBox2.Checked)
            {
                numWhere = " AND num>0";
            }
            else
            {
                numWhere = "";
            }
            string backSelectId = selectcId;
            if (!isRightBtn)
            {
                if (dataGridView1.SelectedRows.Count > 0)
                {
                    dg1SelectIndex = dataGridView1.SelectedRows[0].Index;
                }
                else
                {
                    dg1SelectIndex = 0;
                }
            }
            int dg1SelectIndexBack = dg1SelectIndex;

            if (comboBox2.SelectedValue != null)
            {
                dataGridView1.DataSource = nxsqlHelper.GetDataTableFromSql($"SELECT [id],[cutGroup],[mLength],[num],CONVERT(FLOAT,[cutHeadRate]*100) cutHeadRate,numBack FROM [PM.AiResult] WHERE mID = '{comboBox2.SelectedValue}'{numWhere} order by mLength");
                dg1SelectIndex = dg1SelectIndexBack;
                selectcId = backSelectId;
                dataGridView2.DataSource = nxsqlHelper.GetDataTableFromSql($"SELECT [id],[lg] 长度,[numBack] 计划支数,CASE WHEN cutNum IS NULL THEN 0 ELSE cutNum END 锯切支数,[realNum] 包装支数,numBack - realNum 欠支数 FROM [PM.AiJh]  WHERE mID = '{comboBox2.SelectedValue}'");
                sumResult = Ai.Sum(nxsqlHelper, comboBox2.SelectedValue.ToString());
                label9.Text = sumResult.JhPlanPercent.ToString("0.00") + "%";
                label8.Text = sumResult.JhNoPlanPercent.ToString("0.00") + "%";
                label13.Text = sumResult.RealPercent.ToString("0.00") + "%";
                int.TryParse(nxsqlHelper.GetColumnValue("[PM.Ai]", "noteNum", $"mID = '{comboBox2.SelectedValue}'"), out NoteNum);
                //GetStoreRealMainID(hotStoreRealMainIDNum);
                AutoSelect(checkBox1.Checked, ref noAutoRow);
            }
            else
            {
                dataGridView1.DataSource = nxsqlHelper.GetDataTableFromSql($"SELECT [id],[cutGroup],[mLength],[num],CONVERT(FLOAT,[cutHeadRate]*100) cutHeadRate,numBack FROM [PM.AiResult] WHERE 1=0");
                dataGridView2.DataSource = nxsqlHelper.GetDataTableFromSql($"SELECT [id],[lg] 长度,[numBack] 计划支数,CASE WHEN cutNum IS NULL THEN 0 ELSE cutNum END 锯切支数,[realNum] 包装支数,numBack - realNum 欠支数 FROM [PM.AiJh]  WHERE 1=0");
                NoteNum = 0;
                sumResult = null;
            }
            S3();
        }

        /// <summary>
        /// 获取当班炉号单
        /// </summary>
        private void GetStoreRealMainID(int _hotStoreRealMainIDNum)
        {
            if (comboBox1.SelectedValue != null)
            {
                string isEnd = "isEnd IN (0,1)";
                string sql = $"SELECT DISTINCT TOP({_hotStoreRealMainIDNum}) storeRealMainID,storeRealMainName FROM SB_StoreOutRealMain WHERE {isEnd} AND lineCode = {comboBox1.SelectedValue} ORDER BY storeRealMainID DESC";
                var dt111 = sB_sqlHelper.GetDataTableFromSql(sql);
                BindComboBox(comboBox3, dt111);
                S3();
            }
        }

        /// <summary>
        /// 调用换号系统业务，暂时不用
        /// </summary>
        /// <param name="storeRealMainID"> </param>
        private void HotRollTailAfter(string storeRealMainID)
        {
            string realID = "0";
            string outItemID = "0";
            string lc = "NULL";
            if (textBox6.Tag != null)
            {
                if (double.TryParse(textBox2.Text, out var _lc))
                {
                    lc = _lc.ToString();
                }
                string[] _t = textBox6.Tag.ToString().Split('|');
                if (_t.Length == 2)
                {
                    realID = _t[0];
                    outItemID = _t[1];
                    string insertSql = $@"INSERT INTO SB_p_ItemTable(storeRealMainID,realID,outItemID,outDatatime,hotDataTime,num,hlState,wasteState1,wasteState2,[length],reallength,stepOK) VALUES({comboBox3.SelectedValue},{realID},{outItemID},GETDATE(),NULL,1,0,0,0,{lc},NULL, {1})";
                    if (sB_sqlHelper.ExcuteSql(insertSql) > 0)
                    {
                        var dt = sB_sqlHelper.GetDataTableFromSql($@"SELECT TOP(1) id,
                                   outItemID _outItemID,
                                   K_SteelClass,
                                   num,
                                   DATEPART(HOUR, outDatatime) h,
                                   realID
                            FROM V_SB_p_ItemTable
                            WHERE storeRealMainID = {storeRealMainID}
                                  AND stepOK = 1
                                  AND hlState = 0
                                  AND wasteState1 = 0
                                  AND wasteState2 = 0
                            ORDER BY id ASC");
                        if (dt.Rows.Count > 0)
                        {
                            HotRollTailAfterOp(dt.Rows[0], classTypeID, false);
                        }
                    }
                }
            }
        }

        private bool HotRollTailAfterOp(DataRow item, int classTypeID, bool isHL = false)
        {
            string id = item["pID"].ToString();
            string outitemid = item["_outItemID"].ToString();
            string num = item["num"].ToString();
            int.TryParse(item["h"].ToString(), out var h);
            string dispatchTemplateID = SysInit.GetDispatchTemplateID(h, classTypeID);
            string realID = item["realID"].ToString();
            string hlzs = "0";
            int hlState = 0;
            if (isHL)
            {
                hlzs = num;
                num = "0";
                hlState = 1;
            }
            SqlParameter[] sqlParameter = new SqlParameter[]
            {
                   sB_sqlHelper.CreatSqlParameter("realID", realID, SqlDbType.Int, ParameterDirection.Input),
                   sB_sqlHelper.CreatSqlParameter("outitemid", outitemid, SqlDbType.Int, ParameterDirection.Input),
                   sB_sqlHelper.CreatSqlParameter("usercode", LoginUser.LoginUserCode, SqlDbType.NVarChar, ParameterDirection.Input),
                   sB_sqlHelper.CreatSqlParameter("hlzs", hlzs, SqlDbType.VarChar, ParameterDirection.Input),
                   sB_sqlHelper.CreatSqlParameter("sjzs", num, SqlDbType.VarChar, ParameterDirection.Input),
                   sB_sqlHelper.CreatSqlParameter("dispatchTemplateID", dispatchTemplateID, SqlDbType.VarChar, ParameterDirection.Input),
                   sB_sqlHelper.CreatSqlParameter("pid", id, SqlDbType.Int, ParameterDirection.Input),
                   sB_sqlHelper.CreatSqlParameter("rt", 0, SqlDbType.Int, ParameterDirection.Output)
            };
            sB_sqlHelper.ExcuteProc("U_SB_p_MaterialBack", out var rt, sqlParameter);
            if (rt["@rt"] == "1")
            {
                sB_sqlHelper.ExcuteSql($"UPDATE SB_p_ItemTable SET hlState={hlState},stepOK=stepOK+1 WHERE ID=" + id);
                RecConfirm(id, 1);
                return true;
            }
            return false;
        }

        public static void RecConfirm(string pID, int technologyStepNum)
        {
            sB_sqlHelper.ExcuteSql($@"IF NOT EXISTS (SELECT * FROM SB_p_ItemTableConfirm WHERE pID={pID} AND stepNum={technologyStepNum}) INSERT INTO SB_p_ItemTableConfirm (pID,stepNum,confirmUser,confirmTime) VALUES ({pID},{technologyStepNum},'{LoginUser.LoginUserCode}', GETDATE())");
        }

        private Ai ai;

        /// <summary>
        /// 出钢操作
        /// </summary>
        private void OP()
        {
            double.TryParse(textBox1.Text, out var mLength);
            double.TryParse(textBox2.Text, out var rLength);
            if (rLength < 16 || rLength > 59.5)
            {
                ShowError("原料长度必须在16-59.5之间，当前：" + rLength.ToString());
                return;
            }
            if (comboBox2.SelectedValue == null)
            {
                ShowError("选择生产计划");
                return;
            }
            string mid = comboBox2.SelectedValue.ToString();
            string RealCutGroup = "";
            List<string> upsql = new List<string>();
            bool flag = false;
            int bigMNum = 1;
            int.TryParse(textBox7.Text, out bigMNum);
            if (bigMNum <= 0) bigMNum = 1;
            rLength = mLength;
            if (rLength != mLength)//如果当前长度和理长不一致
            {
                DataTable dt1 = nxsqlHelper.GetDataTableFromSql($"SELECT TOP(1) [cutGroup],mLength FROM [dbo].[PM.AiResult] WHERE mID='{mid}' AND mLength={rLength}");//当前锯切表中存在
                if (dt1.Rows.Count > 0)
                {
                    RealCutGroup = Record(mLength, mid, ref upsql, dt1, bigMNum, rLength);
                }
                else
                {
                    DataTable dt2 = nxsqlHelper.GetDataTableFromSql($@"SELECT TOP(1) cutGroup FROM v_LA_CutTable WHERE mLength = {rLength} AND mainLength IN (SELECT lg FROM [PM.AiJh] WHERE mId = '{mid}' AND numBack-realNum > 0) ORDER BY mainLength DESC");//当前锯切表中不存在，按剩余订单查找锯切组合
                    if (dt2.Rows.Count > 0)
                    {
                        RealCutGroup = Record(mLength, mid, ref upsql, dt2, bigMNum, rLength);
                    }
                    else
                    {
                        DataTable dt3 = nxsqlHelper.GetDataTableFromSql($@"SELECT TOP(1) cutGroup FROM v_LA_CutTable WHERE mLength = {rLength} AND mainLength IN (SELECT lg FROM [PM.AiJh] WHERE mId = '{mid}') ORDER BY mainLength DESC");//当前锯切表中不存在，按全部订单查找锯切组合
                        if (dt3.Rows.Count > 0)
                        {
                            RealCutGroup = Record(mLength, mid, ref upsql, dt3, bigMNum, rLength);
                        }
                    }
                }
                flag = true;
            }
            else//实际长度和理长一致
            {
                DataTable dt0 = nxsqlHelper.GetDataTableFromSql($"SELECT TOP(1)[cutGroup],mLength FROM [PM.AiResult] WHERE id={textBox3.Tag}");
                string[] cutGroup = dt0.Rows[0]["cutGroup"].ToString().Split('=')[1].Split('+');
                upsql.Add($"UPDATE [PM.AiResult] SET num=num-1*{bigMNum} WHERE id={textBox3.Tag}");
                RealCutGroup = Record(mLength, mid, ref upsql, dt0, bigMNum, rLength);
            }
            if (upsql.Any())
            {
                nxsqlHelper.ExcuteSql(upsql);
            }

            label17.Text = RealCutGroup;
            flag = false;//关闭自动计算
            if (flag)
            {
                OneManufacture(mid);
            }
            else
            {
                Reload();
                sumResult = Ai.Sum(nxsqlHelper, mid);
                label9.Text = sumResult.JhPlanPercent.ToString("0.00") + "%";
                label8.Text = sumResult.JhNoPlanPercent.ToString("0.00") + "%";
                label13.Text = sumResult.RealPercent.ToString("0.00") + "%";
                toolStripStatusLabel2.Text = "锯切记录完成！";
            }
        }

        /// <summary>
        /// 自动锯切计算
        /// </summary>
        /// <param name="mid"> </param>
        private void OneManufacture(string mid)
        {
            toolStripProgressBar1.Maximum = 3;
            toolStripProgressBar1.Value = 0;
            toolStripStatusLabel2.Text = "当前按照组合显示区锯切，新锯切表重算中......";
            Task task = Task.Factory.StartNew(() =>
            {
                if (ai == null)
                {
                    ai = new Ai(nxsqlHelper, mid, 6, true);
                }
                else
                {
                    ai.MInit();
                }
                ai.BaseOp();
                Invoke(new Action(() =>
                {
                    toolStripProgressBar1.Value += 1;
                }));

                ai.C2();

                Invoke(new Action(() =>
                {
                    toolStripProgressBar1.Value += 1;
                }));

                ai.C3();

                Invoke(new Action(() =>
                {
                    toolStripProgressBar1.Value += 1;
                }));
            });
            task.ContinueWith(t =>
            {
                Reload();
                toolStripStatusLabel2.Text = "锯切记录完成，锯切表重算完成！";
                SumResult sumResult = Ai.Sum(nxsqlHelper, mid);
                label9.Text = sumResult.JhPlanPercent.ToString("0.00") + "%";
                label8.Text = sumResult.JhNoPlanPercent.ToString("0.00") + "%";
                label13.Text = sumResult.RealPercent.ToString("0.00") + "%";
            }, TaskScheduler.FromCurrentSynchronizationContext());
            toolStripStatusLabel9.Text = LengthAiCalculate.Properties.Settings.Default.logDir;
        }

        private string Record(double mLength, string mid, ref List<string> upsql, DataTable dt, int bigMNum, double rLength)
        {
            string mDatetime = "GETDATE()";
            if (DateTime.TryParse(dateTimePicker1.Value.ToString("yyyy-MM-dd"), out var _mDatetime))
            {
                mDatetime = $"'{_mDatetime:yyyy-MM-dd}'";
            }
            string _cutGroup = dt.Rows[0]["cutGroup"].ToString().Trim();
            upsql.Add($"UPDATE [PM.AiSc] SET realNum=realNum+1*{bigMNum} WHERE mID='{mid}' AND lg={mLength}");
            string[] cutGroup = _cutGroup.Split('=')[1].Split('+');
            foreach (var item in cutGroup)
            {
                string[] _temp = item.Split('*');
                string _length = _temp[0];
                string _num = _temp[1];
                upsql.Add($"UPDATE [PM.AiJh] SET cutNum=ISNULL(cutNum,0)+{_num}*{bigMNum} WHERE mId='{mid}' AND lg={_length}");
                if (textBox6.Text.Trim() != "")
                {
                    upsql.Add($@"IF NOT EXISTS
                (
                    SELECT zzph
                    FROM [PM.AiManufactureResultGroupZZPH]
                    WHERE zzph = '{textBox6.Text.Trim()}'
                          AND [length] = {_length}
                )
                    INSERT INTO [PM.AiManufactureResultGroupZZPH]
                    (
                        zzph,
                        [length],
                        cutNum,
                        packNum
                    )
                    VALUES
                    ('{textBox6.Text.Trim()}', {_length}, ({_num}*{bigMNum}), NULL);
                ELSE
                    UPDATE [PM.AiManufactureResultGroupZZPH]
                    SET cutNum = ISNULL(cutNum,0) + ({_num}*{bigMNum})
                    WHERE zzph = '{textBox6.Text.Trim()}'
                          AND [length] = {_length}");
                }
            }
            if (textBox6.Tag != null)
            {
                string[] _t = textBox6.Tag.ToString().Split('|');
                if (_t.Length == 2)
                {
                    upsql.Add($@"IF NOT EXISTS (SELECT [id] FROM {SysInit.GetSBServer()}[SB_p_CutNumTemp] WHERE realID = {_t[0]} AND rLength={rLength}) INSERT INTO {SysInit.GetSBServer()}SB_p_CutNumTemp (realID,num,rLength) VALUES ({_t[0]},1*{bigMNum},{rLength}); ELSE UPDATE {SysInit.GetSBServer()}SB_p_CutNumTemp SET num = num + 1*{bigMNum} WHERE realID = {_t[0]} AND rLength={rLength}");
                }
                upsql.Add($@"INSERT [PM.AiManufactureResult] (cutGroup,rCutGroup,mLength,rLength,mDatetime,mid,userCode,zzph,resultId,realId,cutNum) VALUES ('{textBox3.Text}','{_cutGroup}',{mLength},{rLength},{mDatetime},'{mid}','{LoginUser.LoginUserCode}','{textBox6.Text.Trim()}','{selectcId}',{_t[0]},{bigMNum})");
            }
            else
            {
                upsql.Add($@"INSERT [PM.AiManufactureResult] (cutGroup,rCutGroup,mLength,rLength,mDatetime,mid,userCode,zzph,resultId,realId,cutNum) VALUES ('{textBox3.Text}','{_cutGroup}',{mLength},{rLength},{mDatetime},'{mid}','{LoginUser.LoginUserCode}','{textBox6.Text.Trim()}','{selectcId}',null,{bigMNum})");
            }
            return _cutGroup;
        }

        private void SumGroupZZPH()
        {
            var dt = nxsqlHelper.GetDataTableFromSql(@"SELECT zzph,
                       rCutGroup,
                       SUM(cutNum) cutNum
                FROM [v.PM.AiManufactureResult]
                WHERE zzph IS NOT NULL
                GROUP BY zzph,
                         rCutGroup");
            List<string> upsql = new List<string>();
            string _cutGroup;
            string[] cutGroup;
            string bigMNum = "0";
            int suc = 0;
            string zzph = "";
            nxsqlHelper.ExcuteSql("DELETE [PM.AiManufactureResultGroupZZPH]");
            foreach (DataRow row in dt.Rows)
            {
                upsql.Clear();
                _cutGroup = row["rCutGroup"].ToString().Trim();
                cutGroup = _cutGroup.Split('=')[1].Split('+');
                bigMNum = row["cutNum"].ToString().Trim();
                zzph = row["zzph"].ToString().Trim();
                foreach (var item in cutGroup)
                {
                    string[] _temp = item.Split('*');
                    string _length = _temp[0];
                    string _num = _temp[1];
                    upsql.Add($@"IF NOT EXISTS
                (
                    SELECT zzph
                    FROM [PM.AiManufactureResultGroupZZPH]
                    WHERE zzph = '{zzph}'
                          AND [length] = {_length}
                )
                    INSERT INTO [PM.AiManufactureResultGroupZZPH]
                    (
                        zzph,
                        [length],
                        cutNum,
                        packNum
                    )
                    VALUES
                    ('{zzph}', {_length}, ({_num}*{bigMNum}), 0);
                ELSE
                    UPDATE [PM.AiManufactureResultGroupZZPH]
                    SET cutNum = ISNULL(cutNum,0) + ({_num}*{bigMNum})
                    WHERE zzph = '{zzph}'
                          AND [length] = {_length}");
                }
                if (nxsqlHelper.ExcuteSql(upsql) > 0) suc++;
            }
        }

        private void TextBox2_TextChanged(object sender, EventArgs e)
        {
            if (textBox2.Text != textBox1.Text)
            {
                label6.Text = "等待";
            }
        }

        public AICalculateFrm aICalculateFrm = new AICalculateFrm();

        private void 计划从排ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ShowQuestion("返回套材计算后，如果需要再进行生产，需要重新保存锯切表，确认该操作吗?") != DialogResult.Yes)
            {
                return;
            }
            if (comboBox2.SelectedValue != null)
            {
                nxsqlHelper.ExcuteSql($"UPDATE [PM.Ai] SET isSave=0 WHERE mID='{comboBox2.SelectedValue}'");
            }
            if (aICalculateFrm == null || !aICalculateFrm.Disposing)
            {
                aICalculateFrm = new AICalculateFrm();
                aICalculateFrm.manufactureFrm = this;
                SetShowFormDefault(aICalculateFrm);
            }
            aICalculateFrm.Show();
            this.Hide();
        }

        private void 启动测长模拟ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "\\NetAssist.exe";
            System.Diagnostics.Process.Start(path);
        }

        /// <summary>
        /// 是否手工选择了组合，true是
        /// </summary>
        private bool noAutoRow = false;

        private string selectcId = "";

        private void TextBox4_Leave(object sender, EventArgs e)
        {
            AutoSelect(checkBox1.Checked, ref noAutoRow);
        }

        private void AutoSelect(bool isNoAuto, ref bool noAutoRow)
        {
            if (Start)
            {
                bool flag = true;
                if (!isNoAuto)
                {
                    dataGridView1.ClearSelection();
                    selectcId = "";
                    foreach (DataGridViewRow item in dataGridView1.Rows)
                    {
                        if (item.Cells["mLength"].Value.ToString().Trim() == textBox4.Text)
                        {
                            textBox1.Text = item.Cells["mLength"].Value.ToString();
                            textBox3.Text = item.Cells["cutGroup"].Value.ToString();
                            textBox3.Tag = item.Cells["cID"].Value.ToString();
                            label6.Text = textBox3.Text;
                            label16.Text = item.Cells["cID"].Value.ToString();
                            textBox5.Text = item.Cells["cutHeadRate"].Value.ToString();
                            item.Selected = true;
                            flag = false;

                            //noAutoRow = true;
                            break;
                        }
                    }
                }
                else
                {
                    if (dataGridView1.SelectedRows.Count == 0 && selectcId == "")
                    {
                        return;
                    }
                    else
                    {
                        int rowIdex = 0;
                        if (selectcId == "")
                        {
                            rowIdex = dataGridView1.SelectedRows[0].Index;
                        }
                        else
                        {
                            foreach (DataGridViewRow item in dataGridView1.Rows)
                            {
                                if (item.Cells["cID"].Value.ToString() == selectcId)
                                {
                                    rowIdex = item.Index;
                                    break;
                                }
                            }
                        }
                        textBox1.Text = dataGridView1.Rows[rowIdex].Cells["mLength"].Value.ToString();
                        textBox3.Text = dataGridView1.Rows[rowIdex].Cells["cutGroup"].Value.ToString();
                        textBox3.Tag = dataGridView1.Rows[rowIdex].Cells["cID"].Value.ToString();
                        label6.Text = textBox3.Text;
                        label16.Text = dataGridView1.Rows[rowIdex].Cells["cID"].Value.ToString();
                        textBox5.Text = dataGridView1.Rows[rowIdex].Cells["cutHeadRate"].Value.ToString();
                        flag = false;
                        noAutoRow = true;
                    }
                }
                if (flag)
                {
                    textBox4.Enabled = true;
                    button1.Text = "开始生产";
                    ShowError("该规格已生产结束，请换规格!");
                }
            }
        }

        /// <summary>
        /// 开始生产
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e">      </param>
        private void Button1_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue == null)
            {
                ShowError("请先选择计划!");
                return;
            }
            noAutoRow = false;
            if (!Start)
            {
                //if (textBox6.Text == "")
                //{
                //    ShowError("轧制批号为空，先输入轧制批号？");
                //    return;
                //}
                double.TryParse(textBox4.Text, out var l);
                if (!checkBox1.Checked && nxsqlHelper.GetCount("[PM.AiSc]", $"mID='{comboBox2.SelectedValue}' AND lg={l}") == 0)
                {
                    ShowError("计划长度必须在计划列表中!");
                    return;
                }
                else
                {
                    Start = true;
                    textBox4.Enabled = false;
                    AutoSelect(checkBox1.Checked, ref noAutoRow);
                    if (checkBox1.Checked && !noAutoRow)
                    {
                        ShowError("请选择一条对应的锯切组合！");
                        return;
                    }
                    button1.Text = "换规格";
                    button2.Enabled = true;
                    comboBox1.Enabled = false;
                    button2.BackColor = System.Drawing.Color.DarkGreen; ;
                    comboBox2.Enabled = false;
                    dg1SelectIndex = dataGridView1.SelectedRows.Count > 0 ? dataGridView1.SelectedRows[0].Index : 0;
                }
            }
            else
            {
                Start = false;
                if (!checkBox1.Checked)
                {
                    textBox4.Enabled = true;
                }
                comboBox2.Enabled = true;
                comboBox1.Enabled = true;
                button2.Enabled = false;
                button2.BackColor = System.Drawing.SystemColors.Control;
                button1.Text = "开始生产";
            }
        }

        private void ManufactureFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void 服务器信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ServerInfo serverInfo = new ServerInfo();
            SetShowFormDefault(serverInfo);
            serverInfo.ShowDialog();
        }

        /// <summary>
        /// 补料通知
        /// </summary>
        private void NoteAddPlan()
        {
            if (sumResult?.JhPlanPercent < 100)
            {
                int lastNum = (int)nxsqlHelper.GetStatistics("[PM.AiJh]", "SUM", "[numBack]-[realNum]", $"mId='{comboBox2.SelectedValue}'");
                string _avgNum = nxsqlHelper.GetDataTableFromSql($@"SELECT COUNT(1)/3 AS num FROM [PM.AiManufactureResult] WHERE mid = '{comboBox2.SelectedValue}' AND mDatetime BETWEEN DATEADD(DAY,-3,GETDATE()) AND GETDATE()")?.Rows[0]["num"].ToString();
                int.TryParse(_avgNum, out var avgNum);
                if (avgNum > 0)
                {
                    int lastHoue = lastNum / avgNum;
                    if (lastHoue < 3 && NoteNum > 0)
                    {
                        SendSMS();
                    }
                }
            }
        }

        private void SendSMS()
        {
            try
            {
                DataTable dt = nxsqlHelper.GetDataTableFromSql($"SELECT lineName FROM [PM.Ai] WHERE mID='{comboBox2.SelectedValue}'");
                if (dt.Rows.Count > 0)
                {
                    Hashtable ht = new Hashtable
                    {
                        { "linename",dt.Rows[0]["lineName"].ToString().Trim() },
                        { "percent",(100.00-sumResult.JhPlanPercent).ToString("0.00")+"%"}
                    };
                    GetApiResult.GetHttpPostDic("http://172.20.16.136/api/pda/SendSMS/", "", "SendManufactureSMS", ht);
                }
                NoteNum--;
                nxsqlHelper.ExcuteSql($"UPDATE [PM.Ai] SET noteNum=noteNum-1 WHERE mID='{comboBox2.SelectedValue}'");
            }
            catch { }
        }

        private void 刷新数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BindComb1();
            dg1SelectIndex = 0;
            Reload(true);
            if (dataGridView1.SelectedRows.Count > 0)
            {
                dataGridView1.SelectedRows[0].Selected = false;
            }
            textBox4.Text = "";
            textBox1.Text = "";
            textBox3.Text = "";
            textBox3.Tag = "";
            label6.Text = textBox3.Text;
            label16.Text = "";
            textBox5.Text = "";
            dg1SelectIndex = 0;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            Reload();
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            S3();
        }

        private int classTypeID = 0;

        private void S3()
        {
            string storeRealMainID = "0";
            if (comboBox3.SelectedValue != null)
            {
                storeRealMainID = comboBox3.SelectedValue.ToString();
            }
            int.TryParse(sB_sqlHelper.GetColumnValue("SB_StoreOutRealMain", "classTypeID", "storeRealMainID=" + storeRealMainID), out classTypeID);
            string sql = $@"SELECT o.ID,
               o.ZZPH,
               o.K_SteelClass,
               o.GGNAMETOEXCLE,
               o.LengthSize,
               o.W,
               o.CountNum,
               o.inRealNum,
               o.HLNum,
               o.wasteNum1,
               o.inLastNum,
               o.K_CPLC,
               o.K_ZXBZ,
               o.K_KZDJ,
               o.K_KWFW,
               o.K_BZ,
               o.SteelClassName,
               o.classTypeName,
               o.userPhoneNum,
               o.UserName,
               o.KZH,
               o.OutItemID,
               CASE WHEN t.num IS NULL THEN 0 ELSE t.num END cutRealNum
               FROM V_SB_StoreOutTraceOnLine o
                   LEFT JOIN [v.PM.AiManufactureCutGroup] t
                       ON o.ID = t.realID
               WHERE o.storeRealMainID = {storeRealMainID} ORDER BY px asc";
            dg3SelectIndex = dataGridView3.FirstDisplayedScrollingRowIndex;
            dataGridView3.DataSource = sB_sqlHelper.GetDataTableFromSql(sql);
            if (textBox6.Tag != null)
            {
                foreach (DataGridViewRow item in dataGridView3.Rows)
                {
                    if (item.Cells["ID3"].Value.ToString() == textBox6.Tag.ToString().Split('|')[0])
                    {
                        item.Selected = true;
                        break;
                    }
                }
            }
            if (dg3SelectIndex != -1 && dataGridView3.Rows.Count > dg3SelectIndex)
            {
                dataGridView3.FirstDisplayedScrollingRowIndex = dg3SelectIndex;
            }
        }

        private AddCutGroup addCutGroup = new AddCutGroup();

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue != null)
            {
                string mId = comboBox2.SelectedValue.ToString();
                if (addCutGroup == null || addCutGroup.Disposing)
                {
                    addCutGroup = new AddCutGroup();
                    addCutGroup.SuccessAction += RefreshData;
                    SetShowFormDefault(addCutGroup);
                }
                addCutGroup.mid = mId;
                addCutGroup.ShowDialog();
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            textBox4.Enabled = !checkBox1.Checked;
            ClickRow();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            ClickRow();
        }

        private void ClickRow()
        {
            if (checkBox1.Checked)
            {
                if (dataGridView1.SelectedRows.Count > 0)
                {
                    //textBox4.Text = dataGridView1.SelectedRows[0].Cells["cutGroup"].Value.ToString().Split('=')[0];
                    textBox1.Text = dataGridView1.SelectedRows[0].Cells["mLength"].Value.ToString();
                    textBox3.Text = dataGridView1.SelectedRows[0].Cells["cutGroup"].Value.ToString();
                    textBox3.Tag = dataGridView1.SelectedRows[0].Cells["cID"].Value.ToString();
                    selectcId = textBox3.Tag.ToString();
                    label6.Text = textBox3.Text;
                    label16.Text = dataGridView1.SelectedRows[0].Cells["cID"].Value.ToString();
                    textBox5.Text = dataGridView1.SelectedRows[0].Cells["cutHeadRate"].Value.ToString();
                    //dg1SelectIndex = dataGridView1.SelectedRows[0].Index;
                }
                else
                {
                    //textBox4.Text = "";
                    textBox1.Text = "";
                    textBox3.Text = "";
                    textBox3.Tag = "";
                    label6.Text = textBox3.Text;
                    label16.Text = "";
                    textBox5.Text = "";
                    dg1SelectIndex = 0;
                }
            }
            else
            {
                textBox4.Text = "";
                textBox1.Text = "";
                textBox3.Text = "";
                textBox3.Tag = "";
                label6.Text = textBox3.Text;
                label16.Text = "";
                textBox5.Text = "";
                dg1SelectIndex = 0;
            }
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            ClickRow();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (editManufacture == null || editManufacture.IsDisposed)
            {
                editManufacture = new EditManufacture();
                editManufacture.DelSuccess = Reload;
                SetShowFormDefault(editManufacture);
            }
            editManufacture.Show();
        }

        private void dataGridView3_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                textBox6.Text = dataGridView3.Rows[e.RowIndex].Cells["ZZPH"].Value.ToString().Trim();
                textBox6.Tag = dataGridView3.Rows[e.RowIndex].Cells["ID3"].Value.ToString().Trim() + "|" + dataGridView3.Rows[e.RowIndex].Cells["OutItemID"].Value.ToString().Trim();
                textBox4.Text = dataGridView3.Rows[e.RowIndex].Cells["K_CPLC"].Value.ToString().Trim();
                AutoSelectCB2(dataGridView3.Rows[e.RowIndex]);
            }
            else
            {
                textBox6.Text = "";
                textBox6.Tag = null;
                textBox4.Text = "";
            }
        }

        private void AutoSelectCB2(DataGridViewRow row)
        {
            string a1 = row.Cells["GGNAMETOEXCLE"].Value.ToString().Trim();
            string a2 = row.Cells["K_SteelClass"].Value.ToString().Trim();
            string a3 = row.Cells["KZH"].Value.ToString().Trim();
            string a = $"{a1}({a2})({a3})";
            int index = 0;
            foreach (DataRowView item in comboBox2.Items)
            {
                if (item[0].ToString() == a || item[1].ToString() == a)
                {
                    comboBox2.SelectedIndex = index;
                    break;
                }
                index++;
            }
            comboBox2.SelectedText = a;
        }

        private int dg3SelectIndex = 0;

        private void button2_Click(object sender, EventArgs e)
        {
            IndicatorLight(button2, timer1, null, 50);
            textBox2.Text = textBox4.Text;
            dg1SelectIndex = dataGridView1.SelectedRows[0].Index;
            if (textBox6.Tag == null)
            {
                ShowError("请先选择轧制批号!");
                return;
            }
            OP();
            if (dg1SelectIndex != -1 && dataGridView1.Rows.Count > dg1SelectIndex)
            {
                dataGridView1.Rows[dg1SelectIndex].Selected = true;
                dataGridView1.FirstDisplayedScrollingRowIndex = dg1SelectIndex;
            }
            //dg3SelectIndex = dataGridView3.FirstDisplayedScrollingRowIndex;
            S3();
            //dataGridView3.FirstDisplayedScrollingRowIndex = dg3SelectIndex;
        }

        public void IndicatorLight(Button btn, Timer timer, Color? newColor, int lightSpeed = 100)
        {
            Color backColor = btn.BackColor;
            timer.Interval = lightSpeed;
            timer.Tick += (object send, EventArgs e) =>
            {
                btn.BackColor = backColor;
                timer1.Enabled = false;
            };
            if (newColor != null)
            {
                btn.BackColor = (Color)newColor;
            }
            else
            {
                btn.BackColor = System.Drawing.Color.Red;
            }
            timer.Stop();
            timer.Dispose();
            timer.Start();
        }

        private void dataGridView3_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            dataGridView3.ClearSelection();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            toolStripStatusLabel7.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (checkBox3.Checked)
            {
                if (DateTime.Now.Hour >= 20 && DateTime.Now.Hour <= 23)
                {
                    dateTimePicker1.Value = DateTime.Now.AddDays(1);
                }
                else
                {
                    dateTimePicker1.Value = DateTime.Now;
                }
            }
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked)
            {
                checkBox3.Text = "自动";
            }
            else
            {
                checkBox3.Text = "手动";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            SumGroupZZPH();
        }
    }
}